var http = require ('http');
const superagent = require ('superagent');
const cheerio = require ('cheerio');
var slog = require ('single-line-log').stdout;
// index 结果校验 0代表下一期 1当前已出奖这期 2上一期 aa bb
// index 结果校验 0代表下一期 1当前已出奖这期 2上一期  11111 2222
// hotfix test
// fix2
let index = 0;
http
  .createServer (async function (request, response) {
    let res = await superagent
      .post ('http://zst.aicai.com/dlt/')
      .type ('form')
      .send ({
        //   maxsize: 200,
        statisticsTag: 1,
        startIssue: 1067,
        endIssue: 10067,
      });
    // .end ((err, res) => {
    //   if (err) {
    //     // 如果访问失败或者出错，会这行这里
    //     console.log (`热点新闻抓取失败 - ${err}`);
    //   } else {
    //     // 访问成功，请求http://news.baidu.com/页面所返回的数据会包含在res
    //     // 抓取热点新闻数据

    //     // hotNews = getHotNews (res);
    //     // console.log(`res:-->`, res);
    //     console.log (`热点新闻抓取`);
    //     return res;
    //   }
    // });

    //   console.log('getHotNews(res) :', getHotNews(res));

    let resp = getHotNews (res);
    //  console.log ('index :', index);

    setInterval (() => {
      let redArr = probability (resp.slice (-35 - index, resp.length - index));
      let res = check (resp, redArr);
      index++;
    }, 100);
    response.writeHead (200, {'Content-Type': 'text/html'});
    response.end (JSON.stringify (resp));
  })
  .listen (8080);

// 终端打印如下信息
console.log ('Server running at http://127.0.0.1:8080/');
let check = (resp, redArr) => {
  slog (index);
  if (index == 0) {
    return ['未开奖'];
  }

  let idx = resp.length - index;
  let arr = resp[idx].red;
  let phase = resp[idx].index;
  let res = redArr.filter (function (n) {
    return arr.indexOf (n) != -1;
  });
  let obj = {[phase + '期开奖结果']: arr, ['预测结果']: redArr, ['预测命中']: res};
  if (res.length > 2) {
    console.log ('index :', index);
    console.log (obj);
  }
  return obj;
};
let getHotNews = res => {
  let hotNews = [];
  // 访问成功，请求http://news.baidu.com/页面所返回的数据会包含在res.text中。

  /* 使用cheerio模块的cherrio.load()方法，将HTMLdocument作为参数传入函数
      以后就可以使用类似jQuery的$(selectior)的方式来获取页面元素
    */
  let $ = cheerio.load (res.text);
  let trArr = $ ('#tdata tr:not(".tdbck")');
  // 找到目标数据所在的页面元素，获取数据
  trArr.each ((idx, ele) => {
    // cherrio中$('selector').each()用来遍历所有匹配到的DOM元素
    // 参数idx是当前遍历的元素的索引，ele就是当前便利的DOM元素
    let obj = {
      red: [],
      blue: [],
    };

    obj.index = $ (ele).children ('td:first-child').text ();
    // console.log ('$(ele): :', $ (ele).text ());
    //  console.log('tr :', tr);
    // console.log("$(ele).children('.yl01')", $(ele).children('.yl01'));
    $ (ele).children ('.chartBall01').each ((index, element) => {
      // console.log ('$ (element).text () :', $ (element).text ());
      obj.red.push ($ (element).text () - 0);
    });
    $ (ele).children ('.chartBall02').each ((index, element) => {
      // console.log ('$ (element).text () :', $ (element).text ());
      obj.blue.push ($ (element).text () - 0);
    });
    hotNews.push (obj);
  });
  return hotNews;
};
let probability = arr => {
  let i = 0;
  let arr2 = [];
  while (i < 35) {
    arr2.push ({[i + 1]: 0});
    i++;
  }

  arr.forEach (element => {
    element.red.forEach (ele => {
      arr2[ele - 1][ele]++;
      // console.log('arr2[ele - 1] :', );
    });
  });

  let res = arr2.sort ((a, b) => {
    return a[Object.keys (a)[0]] - b[Object.keys (b)[0]];
  });
  let redObjArr = arr2.slice (0, 5);
  let redArr = redObjArr.map (ele => {
    return Object.keys (ele)[0] - 0;
  });
  //  console.log ('res :', res);
  //   console.log ('redArr :', redArr);
  return redArr;
};
